# POST r'^authorizations/$'
import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    登录
    自定义jwt认证成功返回数据
    :param token:
    :param request:
    :param user:
    :return:
    """

    return {
        'username': user.username,
        'user_id': user.id,
        'token': token
    }


def get_user_by_account(account):
    """
    判断是用户名,还是手机号码登录
    :param account:
    :return: 数据库查不出来返回None, 查出来返回user
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义手机,用户名登录
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写用户名认证
        :param request:
        :param username:
        :param password:
        :param kwargs:
        :return:
        """
        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user
